#pragma once

#include<iostream>
#include<string>
#include<unordered_map>
#include<fstream>

#include"Log.hpp"

std::string default_path = "dictionary.txt";

class Dictionary
{
private:
    void Load()
    {
        std::ifstream in(_path.c_str());
        if(!in.is_open())
        {
            Log(ERROR,"can not open %s\n",_path);
            exit(-1);
        }
        std::string line;
        while(std::getline(in,line))
        {
            int sep_pos=line.find(' ');
            if(string::npos==sep_pos)
            {
                Log(ERROR,"load item error:%s",line.c_str());
                continue;
            }
            std::string source=line.substr(0,sep_pos);
            std::string destination=line.substr(sep_pos+1,line.size());
            if(destination.empty()||source.empty())
            {
                Log(ERROR,"load item error:%s",line.c_str());
                continue;
            }
            _dict.insert(pair<string,string>(source,destination));
            Log(ERROR,"load item successfully:%s",line.c_str());
        }
        Log(ERROR,"load dictionary successfully");
    }
public:
    Dictionary(std::string path = default_path)
    :_path(path)
    {
        Load();
    }

    std::string Search(std::string source)
    {
        auto it=_dict.find(source);
        if(_dict.end()==it)
        {
            Log(DEBUG,"can find word: %s",source.c_str());
            return std::string();
        }
        Log(DEBUG,"find word sccessfully: %s",source.c_str());
        return it->second;
    }

    ~Dictionary()
    {}

private:
    std::unordered_map<std::string,std::string> _dict;
    std::string _path;
};